import qs from "qs";
import axios from "axios";
import api from "./api";
import { loginRender } from "../components/login/index";

// https://github.com/mzabriskie/axios
// https://github.com/webmodules/jsonp

export const request = function (option) {
	// 默认数据， url and method
	let opt = api[option.api] || {};
	let isJsonUrl = {};
	// application/json   Request/Payload
	if (option.isJson) {
		isJsonUrl.url = opt.url + ((option.jsonArray && option.jsonArray.join("/")) || "");
	}

	if (opt.method && opt.method.toLocaleLowerCase() === "get" && option.data) {
		option.params = option.data;
	} else {
		opt.headers = { "Content-Type": option.contentType || "application/x-www-form-urlencoded" };
		if (!option.isJson) {
			option.data = qs.stringify(option.data);
		}
	}

	let ajaxOpt = Object.assign({}, opt, isJsonUrl, option);
	return axios(ajaxOpt)
		.then(function (res) {
			let data = res.data;
			// 临时处理返回的data没有解析的问题
			if (typeof data === "string") {
				try {
					data = JSON.parse(data);
				} catch (e) {
					try {
						data = eval("(" + data + ")");
					} catch (e) {
						data = {
							result: 100
						};
						console.log(e);
					}
				}
			}
			if (/^1/.test(data.result)) {
				return data;
			} else if (/^7/.test(data.result)) {
				loginRender();
				return Promise.reject(data);
			} else {
				return Promise.reject(data);
			}
		})
		.catch(function (err) {
			console.log(option.api, err);
			return Promise.reject(err);
		});
};
export const requestAll = function (options, spread) {
	let arr = [];
	options.forEach(function (item) {
		let opt = api[item.api] || {};
		let isJsonUrl = {};
		// application/json   Request/Payload
		if (opt.isJson) {
			isJsonUrl.url = opt.url + ((item.jsonArray && item.jsonArray.join("/")) || "");
		}

		if (opt.method && opt.method.toLocaleLowerCase() === "get" && item.data) {
			item.params = item.data;
		} else {
			opt.headers = { "Content-Type": item.contentType || "application/x-www-form-urlencoded" };
			if (!opt.isJson) {
				item.data = qs.stringify(item.data);
			}
		}
		let ajaxOpt = Object.assign({}, opt, item, isJsonUrl);
		arr.push(function () {
			return axios(ajaxOpt);
		}());
	});

	axios.all(arr).then(axios.spread(spread));
};

export const reactFetch = function (option) {
	// 配置
	let params = Object.assign({}, api[option.api] || {}, option);
	// 请求data
	let body = params.contentType === "application/json" ? JSON.stringify(params.data || {}) : qs.stringify(params.data || {});
	// 请求头
	let headers = params.headers || {};
	headers["content-type"] = params.contentType || "application/x-www-form-urlencoded";
	return fetch(params.url, {
		body,
		headers,
		method: params.method || "POST",
		cache: params.cache || "no-cache"
	}).then(response => {
		if (response.ok) {
			let contentType = response.headers.get("content-type");
			if (contentType.includes("application/json")) {
				return response.json();
			} else if (contentType.includes("text/plain")) {
				return response.text();
			} else {
				return response;
			}
		} else {
			return Promise.reject(response);
		}
	}).catch(err => {
		// 捕获fetch示例和之前then方法的错误
		// 然后抛给调用方法的catch，不经过后面的then处理
		// 后面调用方法的catch必须有，不然不会捕获到
		// todo 能不能不写 ？？？？？
		console.log("ajax", err);
		return Promise.reject(err);
	}).then(res => {
		// 临时处理返回的data没有解析的问题
		if (typeof res === "string") {
			try {
				res = JSON.parse(res);
			} catch (e) {
				try {
					res = eval("(" + res + ")");
				} catch (e) {
					res = {
						result: 100
					};
					console.log(e);
				}
			}
		}
		if (/^1/.test(res.result)) {
			return res;
		} else if (/^7/.test(res.result)) {
			loginRender();
			return Promise.reject(res);
		} else {
			return Promise.reject(res);
		}
	});
};
